<template>
  <PopupContainer :is-show="isShow">
    <div class="col-12 q-pa-sm">
      <q-form @submit="onSubmit">
        <div class="page-header row justify-between">
          <div class="col-8" v-if="myAction == 'create'">
            Create New Parts - {{ level }}
          </div>
          <div class="col-8" v-if="myAction == 'edit'">
            Edit Part - {{ level }}
          </div>
          <q-select
            class="col-4"
            style="width: auto"
            :dense="true"
            filled
            :disable="myAction == 'edit'"
            v-model="level"
            :options="levelOps"
          />
        </div>
        <div class="row">
          <div class="col-7 q-pa-sm">
            <q-card>
              <q-card-section>
                <div class="text-h6">Enter Details</div>
                <div class="row">
                  <div class="col-4 fal">
                    <q-item-label>Stock Code:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-4 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.stock_code"
                      use-input
                      :dense="true"
                      hide-bottom-space
                      :disable="myAction == 'edit'"
                      :rules="[
                    (val) =>
                      (val.length == 10 && Number.isInteger(parseInt(val))) ||
                      'Stock Code should be 10 numbers',
                  ]"
                    >
                    </q-input>
                  </div>
                  <q-card-actions class=" col-4">
                    <q-btn class="grey-btn" @click="importDevices">Import Devices</q-btn>
                  </q-card-actions>
                  <div class="col-4 fal">
                    <q-item-label>Serial No:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.serial_no"
                      :dense="true"
                      :disable="myAction == 'edit'"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>System:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-select
                      filled
                      v-model="createForm.data.system"
                      :options="opt.data.system"
                      stack-label
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Car:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.car"
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                    />
                  </div>
                  <div class="col-4 fal">
                    <q-item-label>Work Group:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.workgroup"
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                    />
                  </div>
                  <div class="col-4 fal">
                    <q-item-label>Short Description:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.description"
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Description:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <div style="max-width: 300px">
                      <q-input
                        v-model="createForm.data.detail_description"
                        filled
                        type="textarea"
                      />
                    </div>
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Date Code:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <div style="max-width: 300px">
                      <q-input filled v-model="createForm.data.date_code">
                        <template v-slot:append>
                          <q-icon name="event" class="cursor-pointer">
                            <q-popup-proxy
                              cover
                              transition-show="scale"
                              transition-hide="scale"
                            >
                              <q-date v-model="createForm.data.date_code">
                                <div class="row items-center justify-end">
                                  <q-btn
                                    v-close-popup
                                    label="Close"
                                    color="primary"
                                    flat
                                  />
                                </div>
                              </q-date>
                            </q-popup-proxy>
                          </q-icon>
                        </template>
                      </q-input>
                    </div>
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>S/W Version:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.sw_ver"
                      :dense="true"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>H/W Version:</q-item-label>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-input
                      filled
                      v-model="createForm.data.hw_ver"
                      :dense="true"
                    />
                  </div>
                </div>
              </q-card-section>

              <q-card-section>
                <div class="text-h6">Asset Hierarchy</div>
                <div class="row">
                  <div class="col-4 fal">
                <q-item-label>Equipment Class:</q-item-label
                ><span style="color: red">*</span>
              </div>
              <div class="col-8 q-pa-sm">
                <q-select
                  filled
                  v-model="createForm.data.equipmentClass"
                  :options="opt.data.equipmentClass"
                  stack-label
                  :dense="true"
                  lazy-rules
                  hide-bottom-space
                  :rules="[(val) => val.length > 0 || 'Require field']"
                />
              </div>

                  <div class="col-4 fal">
                    <q-item-label>Level 1:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-select
                      filled
                      v-model="createForm.data.lv1"
                      :options="opt.data.lv1"
                      stack-label
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Level 2:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-select
                      filled
                      v-model="createForm.data.lv2"
                      :options="opt.data.lv2"
                      stack-label
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Level 3:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-select
                      filled
                      v-model="createForm.data.lv3"
                      :options="opt.data.lv3"
                      stack-label
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal">
                    <q-item-label>Level 4:</q-item-label
                    ><span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm">
                    <q-select
                      filled
                      v-model="createForm.data.lv4"
                      :options="opt.data.lv4"
                      stack-label
                      :dense="true"
                      lazy-rules
                      hide-bottom-space
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>

                  <div class="col-4 fal" v-if="level == 'level 5'">
                    <q-item-label>Level 5:</q-item-label>
                    <span style="color: red">*</span>
                  </div>
                  <div class="col-8 q-pa-sm" v-if="level == 'level 5'">
                    <q-select
                      filled
                      v-model="createForm.data.lv5"
                      :options="opt.data.lv5"
                      stack-label
                      :dense="true"
                      :rules="[(val) => val.length > 0 || 'Require field']"
                    />
                  </div>
                </div>
              </q-card-section>
            </q-card>
          </div>
          <div class="col-5 q-pa-sm">
            <QRCodeComponent :qrcode="qrcode" :action="'edit'" />
          </div>
        </div>
        <q-card-actions class="justify-evenly" v-if="myAction == 'create'">
          <q-btn class="grey-btn" type="submit">Save</q-btn>
     
        </q-card-actions>

        <q-card-actions class="justify-evenly" v-if="myAction == 'edit'">
          <q-btn class="grey-btn" @click="getPartsData">Reset</q-btn>
          <q-btn class="grey-btn" type="submit">Save</q-btn>
        </q-card-actions>
      </q-form>
    </div>
  </PopupContainer>
</template>

<script setup lang="ts">
import QRCodeComponent from 'src/components/QRCodeComponent.vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import { DetailFormType, Parts } from 'src/services/type';
import {
  createQrCode,
  editQrCode,
  getPartDetailData,
} from 'src/services/partsService';
import { formatTimeString, formatDateTimeString } from 'src/utils/dateUtils';
import {
  getStockItem,
  getStockItemByStockCode,
} from 'src/services/stockCodeService';
import { useInputOption } from 'src/stores/inputOptionStore';
import PopupContainer from '../container/PopupContainer.vue';

const q = useQuasar();

const levelOps = ['level 4', 'level 5'];
const level = ref('level 4');

const opt = useInputOption();
opt.init();
const props = defineProps<{
  action: 'create' | 'edit';
  partItem?: Parts;
}>();

const isShow = ref(props.action == 'create' ? true : false);

const myAction = ref(props.action);
const myPartItem = ref(props.partItem);

const createForm = reactive<{
  data: DetailFormType;
}>({
  data: {},
});

onMounted(() => {

  createForm.data = {
    ...props.partItem,
  };
});

const route = useRoute();
const qrcode = ref({
  qr_code: '',
  date: '',
  time: '',
});

async function importDevices() {
  const res = await getStockItemByStockCode(createForm.data.stock_code);
  if (res.data) {
    if (res.data.lv5.length == 0) {
      level.value = 'level 4';
    } else {
      level.value = 'level 5';
    }
    createForm.data = { ...res.data };
    createForm.data.parent_part_stock_code = '';
    createForm.data.parent_part_serial_number = '';
  }
}

const emit = defineEmits(['update']);

async function onSubmit() {
  await save();
  emit('update');
}

async function save() {
  if (myAction.value == 'create') {
    const res = await createQrCode(createForm.data);
    if (res.data) {
      qrcode.value = {
        qr_code: JSON.stringify(res.data.qr_code),
        date: res.data.date,
        time: res.data.time,
      };
      q.notify({
        message: 'success',
        color: 'positive',
      });
      myAction.value = 'edit';
      myPartItem.value = {
        ...createForm.data,
        id: res.data.id,
      };
    }
  }
  if (myAction.value == 'edit') {
    if (myPartItem.value) {

      const res = await editQrCode(myPartItem.value.id, createForm.data);
      if (res.data) {

        createForm.data = { ...res.data };

        q.notify({
          message: 'success',
          color: 'positive',
        });
      }
    }
  }
}

async function getPartsData() {
  if (props.partItem?.id) {
    const res = await getPartDetailData(props.partItem?.id);
    if (res.data) {
      if (res.data.lv5.length == 0) {
        level.value = 'level 4';
      } else {
        level.value = 'level 5';
      }
      createForm.data = { ...res.data };
      const date = formatDateTimeString(res.data.create).split(' ', 1);
      qrcode.value = {
        qr_code: JSON.stringify({
          CAT: `${res.data.stock_code}`,
          SN: `${res.data.serial_no}`,
        }),
        date: date[0],
        time: formatTimeString(res.data.create),
      };
    }
  }
}

getPartsData();

const sysOptions = [
  'sysOptions',
  'sysOptions',
  'sysOptions',
  'sysOptions',
  'sysOptions',
];

const eqClassOptions = [
  'EpOptions',
  'EpOptions',
  'EpOptions',
  'EpOptions',
  'EpOptions',
];
const EpOptions = ref(eqClassOptions);

const lv1Options = ['lv1Options'];
const lv2Options = ['lv2Options'];
const lv3Options = ['lv3Options'];
const lv4Options = ['lv4Options'];
const lv5Options = ['lv5Options'];

function filterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      EpOptions.value = eqClassOptions;

      // here you have access to "ref" which
      // is the Vue reference of the QSelect
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    EpOptions.value = eqClassOptions.filter(
      (v) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}
</script>

<style></style>
